import { defineStore } from 'pinia';
import axios from 'axios';

interface QuestionItem {
  content: string;
  image: { uid: number; url: string }[];
  answer: string;
}

interface Notification {
  id: number;
  title: string;
  date: string;
  type: string;
  content: string;
  attachments?: { name: string; url: string }[];
  viewed: boolean;
}

interface Task {
  time: string;
  content: string;
}

interface SearchRecord {
  query: string;
  answer: string;
  searchTime: string;
  answerTime: string;
}

interface Comment {
  id?: number;
  text: string;
  author: string;
  avatar: string;
  timeAgo: string;
}

interface Topic {
  id: number;
  title: string;
  author: string;
  authorAvatar: string;
  authorBio: string;
  timeAgo: string;
  description: string;
  image: string | null;
  video: string | null;
  likes: number;
  commentCount: number;
  isFavorite: boolean;
  comments: Comment[];
}

interface User {
  id: number;
  username: string;
  name: string;
  gender: string;
  email: string;
  avatar: string;
  background: string;
  signature: string;
  followers: number;
  following: number;
  likes: number;
}

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 5000,
  withCredentials: true
});


api.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, error => {
  return Promise.reject(error);
});


api.interceptors.response.use(response => {
  return response.data;
}, error => {
  if (error.response) {
    switch (error.response.status) {
      case 401:
        console.error('未授权，请登录');
        break;
      case 403:
        console.error('拒绝访问');
        break;
      case 404:
        console.error('请求地址出错');
        break;
      case 500:
        console.error('服务器内部错误');
        break;
      default:
        console.error('请求失败');
    }
  } else if (error.request) {
    console.error('无响应，请检查网络连接');
  } else {
    console.error('请求出错', error.message);
  }
  return Promise.reject(error);
});

export const useCounterStore = defineStore('counter', {
  state: () => ({
    local: 'http://localhost:5173',
    AIClassQuestion: '',
    classColor: [
      'linear-gradient(to right, #c467ff, #fe80fb)',
      'linear-gradient(to right, #64acf2, #64edea)',
      'linear-gradient(to right, #f87a8a, #f8c74d)',
      'linear-gradient(to right, #8461FB, #C086FE)',
      'linear-gradient(to right,#FE609A, #FFAA6A)',
      'linear-gradient(to right, #4762F1,#5CC3FE)',
    ],
    AITeach: {
      Step1: { state: 1, content: [] as string[] },
      Step2: { state: 1, content: [] as string[] },
      Step3: { state: 1, content: [] as string[] },
      Step4: { state: 1, content: [] as QuestionItem[] },
      Step5: { state: 1, content: [] as string[] },
      Step6: { state: 1, content: [] as string[] },
    },
    Question: {
      Editor: [] as QuestionItem[],
      Confirm: [
        {
          content: '题目，指考试或练习时要求应试人作答的问题...',
          image: [
            { uid: 1, url: 'https://img1.baidu.com/it/u=2172818577,3783888802&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1422' },
            { uid: 2, url: 'https://img0.baidu.com/it/u=2191392668,814349101&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1399' },
          ],
          answer: '12341111111111111111111111111111111111111111111111111111111111111111567',
        },
        {
          content: '题目，指考试或练习时要求应试人作答的问题...',
          image: [
            { uid: 1, url: 'https://img1.baidu.com/it/u=2172818577,3783888802&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1422' },
            { uid: 2, url: 'https://img0.baidu.com/it/u=2191392668,814349101&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1399' },
          ],
          answer: '1234567',
        },
      ] as QuestionItem[]
    },
    tasks: {} as Record<string, Task[]>,
    searchHistory: [
      {
        query: '如何查询成绩？',
        answer: '请前往学生成绩管理模块查询。',
        searchTime: '2024-01-10 10:00',
        answerTime: '2024-01-10 10:05',
      },
      {
        query: '培养方案是什么？',
        answer: '培养方案是学生的课程规划。',
        searchTime: '2024-01-11 15:30',
        answerTime: '2024-01-11 15:35',
      }
    ] as SearchRecord[],
    notion: {
      monthlyNotifications: {
        '2024年1月': [
          {
            id: 1,
            title: '新学期开学通知',
            date: '2024-01-10',
            type: '通知公告',
            content: '新学期将于2024年1月15日正式开学，请各位同学按时返校报到。',
            attachments: [
              { name: '开学安排.pdf', url: '#' },
              { name: '课程表.xlsx', url: '#' }
            ],
            viewed: false
          },
          {
            id: 2,
            title: '第一周课程安排',
            date: '2024-01-15',
            type: '课程安排',
            content: '第一周课程安排如下：周一上午9:00-11:30 高等数学，下午2:00-4:30 大学英语',
            viewed: false
          },
        ],
        '2月份': [
          {
            id: 3,
            title: '寒假放假通知',
            date: '2024-02-05',
            type: '通知公告',
            content: '根据校历安排，寒假将于2024年2月10日开始，2月25日结束。',
            viewed: false
          },
        ],
      } as Record<string, Notification[]>,
      semesterMonths: ['2024年1月', '2月份', '3月份', '4月份', '5月份', '6月份', '7月份', '8月份'],
      clickedMonths: [] as number[],
      colors: ['#f0f8ff', '#f5f5dc', '#f0fff0', '#fff0f5', '#e6e6fa']
    },
    currentUser: null as User | null
  }),
  getters: {
    getNotificationsByMonth: (state) => (month: string) => {
      return state.notion.monthlyNotifications[month] || []
    },
    getAllMonths: (state) => state.notion.semesterMonths,
    getClickedMonths: (state) => state.notion.clickedMonths,
    getColors: (state) => state.notion.colors,
    isAuthenticated: (state) => !!state.currentUser
  },
  actions: {
    //用户认证
    async login(credentials: { username: string; password: string }) {
      try {
        const response = await api.post('/auth/login', credentials);
        localStorage.setItem('token', response.token);
        this.currentUser = response.user;
        return response;
      } catch (error) {
        console.error('登录失败:', error);
        throw error;
      }
    },

    async logout() {
      try {
        await api.post('/auth/logout');
        localStorage.removeItem('token');
        this.currentUser = null;
      } catch (error) {
        console.error('登出失败:', error);
        throw error;
      }
    },

    async fetchCurrentUser() {
      try {
        const user = await api.get('/auth/me');
        this.currentUser = user;
        return user;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
      }
    },

    // 话题相关API
    async getTopics(page: number = 1, limit: number = 10): Promise<Topic[]> {
      try {
        const response = await api.get('/topics', { params: { page, limit } });
        return response.data;
      } catch (error) {
        console.error('获取话题列表失败:', error);
        return this.getMockTopics();
      }
    },

    async getPostById(id: number): Promise<Topic> {
      try {
        const response = await api.get(`/topics/${id}`);
        return response.data;
      } catch (error) {
        console.error('获取话题详情失败:', error);
        const topics = await this.getMockTopics();
        const topic = topics.find(t => t.id === id);
        if (!topic) throw new Error('话题未找到');
        return topic;
      }
    },

    async getTopicsByAuthor(authorId: number): Promise<Topic[]> {
      try {
        const response = await api.get(`/users/${authorId}/topics`);
        return response.data;
      } catch (error) {
        console.error('获取作者话题失败:', error);
        const topics = await this.getMockTopics();
        return topics.filter(t => t.author === '当前用户');
      }
    },

    async createTopic(topicData: {
      title: string;
      description: string;
      image?: File;
      video?: File;
    }): Promise<Topic> {
      try {
        const formData = new FormData();
        formData.append('title', topicData.title);
        formData.append('description', topicData.description);
        if (topicData.image) formData.append('image', topicData.image);
        if (topicData.video) formData.append('video', topicData.video);

        const response = await api.post('/topics', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        return response.data;
      } catch (error) {
        console.error('创建话题失败:', error);
        throw error;
      }
    },

    async updatePost(postId: number, updatedFields: Partial<Topic>): Promise<Topic> {
      try {
        const response = await api.patch(`/topics/${postId}`, updatedFields);
        return response.data;
      } catch (error) {
        console.error('更新话题失败:', error);
        throw error;
      }
    },

    async deletePost(postId: number): Promise<void> {
      try {
        await api.delete(`/topics/${postId}`);
      } catch (error) {
        console.error('删除话题失败:', error);
        throw error;
      }
    },

    // 评论相关API
    async getComments(postId: number): Promise<Comment[]> {
      try {
        const response = await api.get(`/topics/${postId}/comments`);
        return response.data;
      } catch (error) {
        console.error('获取评论失败:', error);
        throw error;
      }
    },

    async addComment(postId: number, text: string): Promise<Comment> {
      try {
        const response = await api.post(`/topics/${postId}/comments`, { text });
        return response.data;
      } catch (error) {
        console.error('添加评论失败:', error);
        throw error;
      }
    },

    async deleteComment(postId: number, commentId: number): Promise<void> {
      try {
        await api.delete(`/topics/${postId}/comments/${commentId}`);
      } catch (error) {
        console.error('删除评论失败:', error);
        throw error;
      }
    },

    // 点赞收藏相关API
    async likePost(postId: number): Promise<Topic> {
      try {
        const response = await api.post(`/topics/${postId}/like`);
        return response.data;
      } catch (error) {
        console.error('点赞失败:', error);
        throw error;
      }
    },

    async unlikePost(postId: number): Promise<Topic> {
      try {
        const response = await api.delete(`/topics/${postId}/like`);
        return response.data;
      } catch (error) {
        console.error('取消点赞失败:', error);
        throw error;
      }
    },

    async toggleFavorite(postId: number): Promise<Topic> {
      try {
        const response = await api.post(`/topics/${postId}/favorite`);
        return response.data;
      } catch (error) {
        console.error('切换收藏状态失败:', error);
        throw error;
      }
    },

    async getFavorites(userId: number): Promise<Topic[]> {
      try {
        const response = await api.get(`/users/${userId}/favorites`);
        return response.data;
      } catch (error) {
        console.error('获取收藏列表失败:', error);
        throw error;
      }
    },

    // 用户相关API
    async getUserProfile(userId: number): Promise<User> {
      try {
        const response = await api.get(`/users/${userId}`);
        return response.data;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
      }
    },

    async updateUserProfile(userId: number, userData: Partial<User>): Promise<User> {
      try {
        const response = await api.patch(`/users/${userId}`, userData);
        return response.data;
      } catch (error) {
        console.error('更新用户信息失败:', error);
        throw error;
      }
    },

    async uploadAvatar(userId: number, file: File): Promise<User> {
      try {
        const formData = new FormData();
        formData.append('avatar', file);

        const response = await api.post(`/users/${userId}/avatar`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        return response.data;
      } catch (error) {
        console.error('上传头像失败:', error);
        throw error;
      }
    },

    async uploadBackground(userId: number, file: File): Promise<User> {
      try {
        const formData = new FormData();
        formData.append('background', file);

        const response = await api.post(`/users/${userId}/background`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        return response.data;
      } catch (error) {
        console.error('上传背景失败:', error);
        throw error;
      }
    },

    async getMockTopics(): Promise<Topic[]> {
      return [
        {
          id: 1,
          title: 'Vue3+TypeScript项目实践分享',
          author: '陈工程师',
          authorAvatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          authorBio: '资深前端工程师，专注于Vue和TypeScript开发。',
          timeAgo: '2023.10.01',
          description: '最近在项目中使用Vue3+TypeScript开发，积累了一些经验和心得，在这里和大家分享讨论。',
          image: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          video: null,
          likes: 12,
          commentCount: 1,
          isFavorite: false,
          comments: [
            {
              text: '非常实用的分享！',
              author: '用户A',
              avatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
              timeAgo: '2023.10.01',
            },
          ],
        },
        {
          id: 2,
          title: '前端性能优化技巧',
          author: '李设计师',
          authorAvatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          authorBio: '前端开发与设计双修，热衷于性能优化。',
          timeAgo: '2023.09.28',
          description: '分享一些前端性能优化的实用技巧，包括代码优化、资源加载、缓存策略等。',
          image: null,
          video: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          likes: 8,
          commentCount: 8,
          isFavorite: true,
          comments: [
            {
              text: '学到了很多，感谢分享！',
              author: '用户C',
              avatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
              timeAgo: '2023.09.28',
            },
          ],
        },
        {
          id: 3,
          title: '前端性能优化技巧',
          author: '李设计师',
          authorAvatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          authorBio: '前端开发与设计双修，热衷于性能优化。',
          timeAgo: '2021.09.28',
          description: '分享一些前端性能优化的实用技巧，包括代码优化、资源加载、缓存策略等。',
          image: null,
          video: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          likes: 8,
          commentCount: 8,
          isFavorite: true,
          comments: [
            {
              text: '学到了很多，感谢分享！',
              author: '用户C',
              avatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
              timeAgo: '2023.09.28',
            },
          ],
        },
        {
          id: 4,
          title: '前端性能优化技巧',
          author: '李设计师',
          authorAvatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          authorBio: '前端开发与设计双修，热衷于性能优化。',
          timeAgo: '2025.09.28',
          description: '分享一些前端性能优化的实用技巧，包括代码优化、资源加载、缓存策略等。',
          image: null,
          video: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          likes: 8,
          commentCount: 8,
          isFavorite: true,
          comments: [
            {
              text: '学到了很多，感谢分享！',
              author: '用户C',
              avatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
              timeAgo: '2023.09.28',
            },
          ],
        },
        {
          id: 5,
          title: '前端性能优化技巧',
          author: '李设计师',
          authorAvatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          authorBio: '前端开发与设计双修，热衷于性能优化。',
          timeAgo: '2024.09.28',
          description: '分享一些前端性能优化的实用技巧，包括代码优化、资源加载、缓存策略等。',
          image: null,
          video: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          likes: 8,
          commentCount: 8,
          isFavorite: true,
          comments: [
            {
              text: '学到了很多，感谢分享！',
              author: '用户C',
              avatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
              timeAgo: '2023.09.28',
            },
          ],
        },
      ];
    },

    addClickedMonth(index: number) {
      if (!this.notion.clickedMonths.includes(index)) {
        this.notion.clickedMonths.push(index);
      }
    },
    changeEditor(index: number, newItem: any) {
      this.$patch({
        Question: {
          Editor: this.Question.Editor.map((item, i) =>
              i === index ? newItem : item
          )
        }
      });
    },
    deleteEditorImage(index: number, imageIndex: number) {
      this.$patch((state) => {
        state.Question.Editor[index].image.splice(imageIndex, 1);
      });
    },
    addEditorImage(index: number, file: { uid: number; url: string }) {
      this.$patch((state) => {
        state.Question.Editor[index].image.push(file);
      });
    },
    addQuestionToConfirm(index: any) {
      if (index >= 0 && index < this.Question.Editor.length) {
        const question = JSON.parse(JSON.stringify(this.Question.Editor[index]));
        this.Question.Editor.splice(index, 1);
        this.Question.Confirm.push(question);
      } else {
        console.error('习题添加失败');
      }
    },
    deleteQuestionFromConfirm(index: any) {
      if (index >= 0 && index < this.Question.Confirm.length) {
        const question = JSON.parse(JSON.stringify(this.Question.Confirm[index]));
        this.Question.Confirm.splice(index, 1);
        this.Question.Editor.push(question);
      } else {
        console.error('习题转移失败');
      }
    },
    addAIteachStep1(content: any) {
      this.$patch((state) => {
        state.AITeach.Step1.content = content;
      });
    },
    addAIteachStep2(content: any) {
      this.$patch((state) => {
        state.AITeach.Step2.content = content;
      });
    },
    addAIteachStep3(content: any) {
      this.$patch((state) => {
        state.AITeach.Step3.content = content;
      });
    },
    addAIteachStep4(content: any) {
      this.$patch((state) => {
        state.AITeach.Step4.content = content;
      });
    },
    addAIteachStep5(content: any) {
      this.$patch((state) => {
        state.AITeach.Step5.content = content;
      });
    },
    addAIteachStep6(content: any) {
      this.$patch((state) => {
        state.AITeach.Step6.content = content;
      });
    },
    getQuestion(content: any) {
      this.$patch((state) => {
        state.Question.Editor = content;
      });
    },
    clearConfirmQuestion() {
      this.$patch((state) => {
        state.Question.Confirm = [] as QuestionItem[];
      });
    },
    getAIClassQuestion(text: any) {
      this.$patch((state) => {
        state.AIClassQuestion = text;
      });
    },


    async fetchTasks() {
      try {
        return new Promise((resolve) => {
          setTimeout(() => {
            this.tasks = {
              '2024-01-15': [
                { time: '09:00', content: '参加团队会议' },
                { time: '14:00', content: '完成项目报告' }
              ]
            };
            resolve(this.tasks);
          }, 500);
        });
      } catch (error) {
        console.error('获取任务失败:', error);
        throw error;
      }
    },

    async addTask(date: string, task: Task) {
      try {
        // Mock API call
        return new Promise((resolve) => {
          setTimeout(() => {
            if (!this.tasks[date]) {
              this.tasks[date] = [];
            }
            this.tasks[date].unshift(task);
            resolve(task);
          }, 300);
        });
      } catch (error) {
        console.error('添加任务失败:', error);
        throw error;
      }
    },


    async fetchMonthlyNotifications() {
      try {
        return new Promise((resolve) => {
          setTimeout(() => {
            // Data is already initialized in state
            resolve(this.notion.monthlyNotifications);
          }, 500);
        });
      } catch (error) {
        console.error('获取通知失败:', error);
        throw error;
      }
    },

    async markNotificationAsRead(month: string, id: number) {
      try {

        return new Promise((resolve) => {
          setTimeout(() => {
            const notification = this.notion.monthlyNotifications[month]?.find(n => n.id === id);
            if (notification) {
              notification.viewed = true;
            }
            resolve(true);
          }, 300);
        });
      } catch (error) {
        console.error('标记通知为已读失败:', error);
        throw error;
      }
    },


    async search(query: string) {
      try {

        return new Promise((resolve) => {
          setTimeout(() => {
            const mockAnswers: Record<string, string> = {
              '成绩': '您可以在学生门户的成绩查询页面查看您的成绩。',
              '课程': '当前学期的课程安排已发布在通知公告中。',
              '考试': '期末考试时间表将在考试前两周公布。'
            };

            const answer = mockAnswers[query] || `关于"${query}"的搜索结果，请咨询教务处获取更多信息。`;

            const newRecord = {
              query,
              answer,
              searchTime: new Date().toLocaleString(),
              answerTime: new Date().toLocaleString()
            };

            this.searchHistory.unshift(newRecord);
            resolve(newRecord);
          }, 500);
        });
      } catch (error) {
        console.error('搜索失败:', error);
        throw error;
      }
    },
  }
});